package com.haiyi.software.app;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RelativeLayout.LayoutParams;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.haiyi.software.app.basic.ActivityPersonalBasicCancelFollow;
import com.haiyi.software.entity.EntityUserPhoto;
import com.haiyi.software.entity.UserFriend;
import com.haiyi.software.tools.L;
import com.haiyi.software.tools.MyTools;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

public class ActivityPersonal extends ActivityPersonalBasicCancelFollow
		implements OnClickListener {

	private MyTools tools = MyTools.getInstance();

	private TextView textView_personalName;

	private TextView textView_sex;

	private TextView textview_theCharm;

	private TextView textview_theGiftsGolds;

	private TextView textview_theUid;

	private TextView textView_theUname;

	private TextView textview_theBody;

	private TextView textview_theBirthday;

	private TextView textview_theJob;

	private TextView textview_theIncome;

	private TextView textview_mynews;

	private TextView textView_constellation;

	private TextView textview_thSex;

	private RadioButton rd_chat;

	private RadioButton rd_follow;

	private RadioButton rd_gift;

	private GridView gridViewImgList;

	private List<Map<String, EntityUserPhoto>> list;

	private MyAdapter mydpt;

	private DisplayImageOptions options, options_fm;

	private ImageLoader imageLoader;

	private Button button;

	private PullToRefreshScrollView pull_refresh_scrollview;

	private TextView textView_juli;

	private TextView textView_time;

	private String strUID;

	private ImageView img_person_head;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_personal);
		// TODO 自动生成的方法存根

		getParameter();

		initComp();

		initData();

		handlerLoad.sendEmptyMessageDelayed(1, 300);
	}

	Handler handlerLoad = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO 自动生成的方法存根
			super.handleMessage(msg);
			pull_refresh_scrollview.setRefreshing();
		}

	};

	private void initData() {
		// TODO 自动生成的方法存根
		// getPersonInfo(strUID);
	}

	private void initComp() {

		DisplayMetrics metric = new DisplayMetrics();

		getWindowManager().getDefaultDisplay().getMetrics(metric);

		int width = metric.widthPixels; // 屏幕宽度（像素）
		// int height = metric.heightPixels; // 屏幕高度（像素）

		L.i("width=" + width);

		img_person_head = (ImageView) this.findViewById(R.id.img_person_head);

		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, width);

		img_person_head.setLayoutParams(params);

		pull_refresh_scrollview = (PullToRefreshScrollView) this
				.findViewById(R.id.pull_refresh_scrollview);

		textview_mynews = (TextView) this.findViewById(R.id.textview_mynews);
		textView_personalName = (TextView) this
				.findViewById(R.id.textView_personalName);
		textView_sex = (TextView) this.findViewById(R.id.textView_sex);
		textview_theBirthday = (TextView) this
				.findViewById(R.id.textview_theBirthday);
		textview_theBody = (TextView) this.findViewById(R.id.textview_theBody);
		// textview_theGiftsGolds = (TextView) this
		// .findViewById(R.id.textview_theGiftsGolds);
		textview_theCharm = (TextView) this
				.findViewById(R.id.textview_theCharm);
		textview_theIncome = (TextView) this
				.findViewById(R.id.textview_theIncome);
		textview_theJob = (TextView) this.findViewById(R.id.textview_theJob);
		textview_theUid = (TextView) this.findViewById(R.id.textview_theUid);
		textView_theUname = (TextView) this
				.findViewById(R.id.textView_theUname);
		textView_constellation = (TextView) this
				.findViewById(R.id.textView_constellation);
		textview_thSex = (TextView) this.findViewById(R.id.textview_thSex);

		textView_time = (TextView) this.findViewById(R.id.textView_time);

		textView_juli = (TextView) this.findViewById(R.id.textView_juli);

		gridViewImgList = (GridView) this
				.findViewById(R.id.gridview_personImgList);

		rd_chat = (RadioButton) this.findViewById(R.id.rd_main_tb_chat);
		rd_follow = (RadioButton) this.findViewById(R.id.rd_main_tb_follow);
		rd_gift = (RadioButton) this.findViewById(R.id.rd_main_tb_gift);

		rd_chat.setOnClickListener(this);
		rd_follow.setOnClickListener(this);
		rd_gift.setOnClickListener(this);

		// 图片控件*********************************************
		imageLoader = ImageLoader.getInstance();
		options = new DisplayImageOptions.Builder()
				.imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
				.showImageOnLoading(R.drawable.ic_launcher)
				.showImageForEmptyUri(R.drawable.ic_launcher)
				.showImageOnFail(R.drawable.ic_launcher).cacheInMemory(true)
				.cacheOnDisc(true).considerExifParams(true)
				.displayer(new RoundedBitmapDisplayer(10)).build();
		options_fm = new DisplayImageOptions.Builder()
				.imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
				.showImageOnLoading(R.drawable.mv)
				.showImageForEmptyUri(R.drawable.mv)
				.showImageOnFail(R.drawable.mv).cacheInMemory(true)
				.cacheOnDisc(true).considerExifParams(true)
				.displayer(new RoundedBitmapDisplayer(0)).build();
		// *****************************************************

		// 初始化变量
		mydpt = new MyAdapter(this);
		list = new ArrayList<Map<String, EntityUserPhoto>>();

		this.gridViewImgList = (GridView) this
				.findViewById(R.id.gridview_personImgList);

		// 右上角按钮
		button = (Button) this.findViewById(R.id.nextBtn_username);

		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				// TODO 自动生成的方法存根
				showMenu(ActivityPersonal.this, v);
			}
		});

		pull_refresh_scrollview.setOnRefreshListener(RefreshListener);
	}

	private OnRefreshListener<ScrollView> RefreshListener = new OnRefreshListener<ScrollView>() {

		@Override
		public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
			// TODO 自动生成的方法存根
			getPersonInfo(strUID);
		}
	};

	/**
	 * 页面传奇的。获取参数
	 */
	private void getParameter() {
		// TODO 自动生成的方法存根
		strUID = this.getIntent().getStringExtra("uid");
	}

	@Override
	public void requestFinish(JsonObject jsonObjectReturn) {
		// TODO 自动生成的方法存根

		// 用于举报
		this.button.setTag(mapUser);

		JsonArray ucovers = (JsonArray) mapUser.get("uCovers");

		if (ucovers.size() > 0) {
			imageLoader.displayImage(str_server
					+ ucovers.get(0).getAsJsonObject().get("phobig")
							.getAsString(), img_person_head, options_fm);
		}

		textView_personalName.setText(mapUser.get("username") != null ? mapUser
				.get("username").toString() : "");

		textView_sex.setBackgroundResource(tools.getSexBackground(mapUser.get(
				"usex").toString()));

		textView_sex.setText(mapUser.get("age") != null ? mapUser.get("age")
				.toString() : "");

		textView_time.setText(tools.beautifulDateTime(mapUser
				.get("lastdatetime") != null ? mapUser.get("lastdatetime")
				.toString() : "1970-1-1"));

		textView_juli
				.setText(tools.beautifulDistance(mapUser.get("juli") != null ? mapUser
						.get("juli").toString() : "-1"));

		textView_sex.setGravity(Gravity.CENTER_VERTICAL);
		textView_sex.setPadding(40, 2, 5, 0);

		textview_theBirthday.setText(mapUser.get("ubirthday") != null ? mapUser
				.get("ubirthday").toString() : "");

		textview_theBody.setText(mapUser.get("ubody") != null ? mapUser.get(
				"ubody").toString() : "");

		// textview_theGiftsGolds.setText("")

		textview_theCharm.setText(mapUser.get("vgold") != null ? mapUser.get(
				"vgold").toString() : "");

		textview_theIncome.setText(mapUser.get("umoney") != null ? mapUser.get(
				"umoney").toString() : "");

		textview_theJob.setText(mapUser.get("uwork") != null ? mapUser.get(
				"uwork").toString() : "");

		textview_theUid.setText(mapUser.get("uid") != null ? mapUser.get("uid")
				.toString() : "");

		textView_theUname.setText(mapUser.get("uname") != null ? mapUser.get(
				"uname").toString() : "");

		textview_mynews
				.setText(mapUser.get("sign").toString().length() > 0 ? mapUser
						.get("sign").toString() : "未填写");

		textview_thSex.setText(MyTools.getInstance().getSexNameBySexID(
				mapUser.get("usex").toString()));

		textView_constellation.setText(mapUser.get("ustar") != null ? mapUser
				.get("ustar").toString() : "");

		String rstate = mapUser.get("rstate") != null ? mapUser.get("rstate")
				.toString() : "0";

		if (rstate.equals("1") || rstate.equals("3")) {

			rd_follow.setText("取消");

		} else {

			rd_follow.setText("关注");
		}

		// 加载图片地址*****************************

		JsonArray headAry = (JsonArray) mapUser.get("uhead");

		Map<String, EntityUserPhoto> map = null;

		list.clear();

		if (headAry.size() > 0) {

			for (JsonElement item : headAry) {

				map = new HashMap<String, EntityUserPhoto>();

				EntityUserPhoto userPhoto = new EntityUserPhoto();

				userPhoto.setAttuid(item.getAsJsonObject().get("attuid")
						.getAsString());

				userPhoto.setPhobig(str_server
						+ item.getAsJsonObject().get("phobig").getAsString());

				userPhoto.setPhosmall(str_server
						+ item.getAsJsonObject().get("phosmall").getAsString());

				map.put("itemPhoto", userPhoto);

				list.add(map);
			}

		} else {

		}
		// ***************************************

		gridViewImgList.setAdapter(mydpt);

		pull_refresh_scrollview.onRefreshComplete();
	}

	@Override
	public void onClick(View v) {
		// TODO 自动生成的方法存根
		switch (v.getId()) {
		case R.id.rd_main_tb_chat:
			UserFriend friend = new UserFriend();

			if (mapUser != null) {

				friend.setUfName(mapUser.get("username") != null ? mapUser.get(
						"username").toString() : "");

				friend.setUfID(mapUser.get("uid") != null ? mapUser.get("uid")
						.toString() : "");

				friend.setUfPhoto(mapUser.get("headSmall") != null ? mapUser
						.get("headSmall").toString() : "");

				Bundle bundleUF = new Bundle();

				bundleUF.putSerializable("com.hichat.UserFriend", friend);

				Intent chatIntent = new Intent(this, HiChat.class);

				chatIntent.putExtras(bundleUF);

				startActivity(chatIntent);
			}

			break;
		case R.id.rd_main_tb_follow:

			if (mapUser != null) {

				if (rd_follow.getText().toString().equals("关注")) {
					setFollow(strUID, mapUser.get("uname") != null ? mapUser
							.get("uname").toString() : "");
				} else if (rd_follow.getText().toString().equals("取消")) {

					cancelFollow(strUID, mapUser.get("uname") != null ? mapUser
							.get("uname").toString() : "");
				}

			}

			break;
		case R.id.rd_main_tb_gift:
			if (mapUser != null) {

				Intent giftIntent = new Intent(this, ActivityGiftLists.class);

				giftIntent.putExtra("UID", strUID);

				startActivityForResult(giftIntent, 10016);
			}
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		switch (requestCode) {
		case 10016:
			getPersonInfo(strUID);
			break;

		default:
			break;
		}

	};

	private class MyAdapter extends BaseAdapter {

		private Context context;

		private LayoutInflater inflater;

		public MyAdapter(Context context) {

			this.context = context;
			this.inflater = LayoutInflater.from(context);

		}

		@Override
		public int getCount() {

			// TODO 自动生成的方法存根
			return list.size();

		}

		@Override
		public Object getItem(int position) {

			// TODO 自动生成的方法存根

			return list.get(position);
		}

		@Override
		public long getItemId(int position) {

			// TODO 自动生成的方法存根
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {

			ViewHolder viewHolder = null;

			convertView = inflater.inflate(R.layout.item_imglist, null);
			viewHolder = new ViewHolder();

			viewHolder.imgHolder = (ImageView) convertView
					.findViewById(R.id.img_personImgList);

			viewHolder.btnImg = (Button) convertView
					.findViewById(R.id.item_n_btn);

			convertView.setTag(viewHolder);

			imageLoader.displayImage(list.get(position).get("itemPhoto")
					.getPhosmall(), viewHolder.imgHolder, options);

			viewHolder.btnImg.setTag(list.get(position).get("itemPhoto")
					.getAttuid());

			viewHolder.btnImg.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO 自动生成的方法存根
					startImagePagerActivity(position);
				}
			});

			// TODO 自动生成的方法存根
			return convertView;
		}
	}

	private void startImagePagerActivity(int position) {
		Intent intent = new Intent(this, ImagePagerActivity.class);

		intent.putExtra("images", (Serializable) list);
		intent.putExtra("position", position);
		startActivity(intent);
	}

	private static class ViewHolder {

		ImageView imgHolder;
		Button btnImg;
	}

	@Override
	protected void followReturn(JsonElement jsonReturn) {

		// TODO 自动生成的方法存根
		if (jsonReturn != null) {
			if (jsonReturn.getAsJsonObject().get("state") != null) {

				Toast.makeText(this,
						jsonReturn.getAsJsonObject().get("desc").toString(),
						Toast.LENGTH_SHORT).show();

				String state = jsonReturn.getAsJsonObject().get("state")
						.getAsString();

				if (state.equals("200") || state.equals("208")) {
					rd_follow.setText("取消");
				}
			}
		}
	}

	@Override
	protected void requestError() {
		// TODO 自动生成的方法存根
		Toast.makeText(this, "网络连接错误", Toast.LENGTH_SHORT).show();
		pull_refresh_scrollview.onRefreshComplete();
	}

	@Override
	protected void cancelFollowReturn(JsonObject jsonReturn) {
		// TODO 自动生成的方法存根
		if (jsonReturn != null) {

			Toast.makeText(this, jsonReturn.get("desc").toString(),
					Toast.LENGTH_SHORT).show();
			if (jsonReturn.get("state").getAsString().equals("200")) {

				rd_follow.setText("关注");
			}
		}
	}
}
